const app = getApp()
let utils = require('../../utils/util.js')

Page({
  data: {
    partId: '',
    groupId: '',
    groupNo: '',   //团号
    scrollHeight: 0,        //"滚动视图的高度"
    topIcon: '',
    detailImg: '',
    completeNum: 15, //已团购数量
    groupendNum: 3,  //成团人数
    leftNum: 1,       //还差多少人成团
    groupendNumWord: '',  //成团人数大写
    goodName: "",          //商品名称
    recipe: "",     //配方
    price: 300,          //原价
    groupPrice: 200,       //团购价
    personList: null,
    leftTime: 88,            //剩余时间
    leftTimeStr: ['', '', ''],     //剩余的时间数组
    intervalId: -1000,           //刷新现成团计时器id
    pollInterval: 2,            //轮询间隔的时间
    pollConut: 0,               //轮询计时
    groupState: "1",            //拼团的状态 1进行中 2拼团成功 3拼团失败
    groupIconUrl: '',
    inList: false,              //用户是否在拼团的列表中
    hasInit: false,
    payWaitReflash: false,     //已经支付了，等待刷新
    share: false,              //是否是分享的内容
    showHint: false,           //分享提示层
    dialog: null,
    animationData: {},
    animation: null,
    homeStatus: 'out',
  },
  onLoad(options) {
    console.log("获取到的参数id=" + options.id)
    console.log("获取到的参数share=" + options.share)
    if (options.share) this.data.share = true
    // app.globalData.token='138409283';
    // this.data.share = true;
    this.data.groupNo = options.id
    if (app.globalData.authorization || this.data.share) {
      app.toggleLoading(true)
      this.requestData()
    }
    //创建动画
    var animation = wx.createAnimation({
      timingFunction: 'ease',
    })
    this.animation = animation
  },
  onShow() {
    if (app.globalData.authorization) {
      console.log('已经授权过了...')
      if (this.data.dialog) {
        this.data.dialog.hideDialog()
        this.data.dialog = null
      }
    }
    else if (!this.data.dialog) {
      this.data.dialog = this.selectComponent("#dialog")
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.userInfo']) {     //未授权
            this.data.dialog.showDialog()
            console.log('获取设置没有授权...')
          } else {
            app.globalData.authorization = true
            console.log('获取已经授权了...')
            if (!this.data.share) {
              app.toggleLoading(true)
              this.requestData()
            }
          }
        }
      })
    }
    if (!this.data.hasInit) return
    if (this.data.groupState.toString() !== '1') return
    this.data.pollConut = 0
    this.refreshGroupState()
  },
  //弹出框确认事件
  _confirmEvent() {
    app.globalData.authorization = true
    this.data.dialog.hideDialog()
    this.data.dialog = null
    if (!this.data.share) {
      app.toggleLoading(true)
      this.requestData()
    }
  },
  myCatchTouch() {

  },
  onHide: function () {
    //this.removeInterval();
    console.log('参团界面onHide....')
  },
  /**
   * 当页面销毁时调用
   */
  onUnload: function () {
    this.removeInterval()
    console.log('参团界面onUnload....')
  },
  requestData() {
    let data = {groupNo: this.data.groupNo}
    if (this.data.share) data.share = 1
    app.post('user/order/info', data, this, this.requestData, []).then((res) => {
      if (!this.data.hasInit) this.data.hasInit = true
      let resultObj = res.data.data
      this.data.partId = resultObj.partId
      this.data.groupId = resultObj.groupId
      this.setData({
        'completeNum': resultObj.groupendNum,
        'groupendNum': resultObj.groupNum,
        'goodName': resultObj.itemName,
        'price': resultObj.price,
        'groupPrice': resultObj.groupPrice,
        'recipe': resultObj.itemSuggest,
        'topIcon': resultObj.itemImage,
        'detailImg': resultObj.detailImage,
        leftTime: parseInt(resultObj.leftTime),
        groupendNumWord: utils.convertChinese(resultObj.groupNum)
      })
      let exitingArr = resultObj.orderList
      this.initPersonList(exitingArr)
      this.setData({groupState: resultObj.groupStatus.toString(), inList: this.data.inList}, () => {
        app.toggleLoading(false)
        this.updataScrollViewH()
        this.updataGroupIconUrl()

        if (this.data.groupState === "1") {
          this.addInterval()
          this.refreshExistingTime()
        }
      })
    }).catch((errMsg) => {
      console.log(errMsg)    //错误提示信息
    })
  },
  initPersonList(exitingArr) {                                  //初始化人员数组
    let leftNum = this.data.groupendNum - exitingArr.length
    this.setData({'leftNum': leftNum})
    this.data.personList = []
    let personList = this.data.personList
    for (let i = 0; i < this.data.groupendNum; i++) {
      let item = {'order': i.toString()}         //order排序
      if (i < exitingArr.length) {
        let exiting = exitingArr[i]
        item.userHead = exiting.userHead
        console.log('app.globalData.token=' + app.globalData.token)
        console.log('exiting.userToken=' + exiting.userToken)
        if (app.globalData.token == exiting.userToken) {
          this.data.inList = true
        }
      }
      personList.push(item)
    }
    this.setData({"personList": personList})
  },
  refreshPersonList(exitingArr) {                       //更新人员数组
    if (exitingArr.length === this.data.groupendNum - this.data.leftNum) return   //没有新的人进来
    let leftNum = this.data.groupendNum - exitingArr.length
    this.setData({'leftNum': leftNum})

    let personList = this.data.personList
    for (let i = 0; i < this.data.groupendNum; i++) {
      let item = personList[i]
      if (i < exitingArr.length) {
        let exiting = exitingArr[i]
        item.userHead = exiting.userHead
        console.log('app.globalData.token=' + app.globalData.token)
        console.log('exiting.userToken=' + exiting.userToken)
        if (!this.data.inList && app.globalData.token == exiting.userToken) {
          this.data.inList = true
          this.setData({inList: true}, () => {
            this.updataScrollViewH()
          })
        }
      }
    }
    this.setData({"personList": personList})
  },
  updataGroupIconUrl() {
    if (this.data.groupState === '1') {
      this.setData({groupIconUrl: '../../images/underway_icon.png'})
    } else if (this.data.groupState === '2') {
      this.setData({groupIconUrl: '../../images/group_sucess_icon.png'})
    } else {
      this.setData({groupIconUrl: '../../images/fail_group_icon.png'})
    }
  },
  joinHandle() {
    if (this.data.inList) {
      wx.showToast({title: '您已在该商品团购中了', icon: 'none'})
      return
    }
    app.toggleLoading(true)
    console.log('app.globalData.token=' + app.globalData.token)
    app.post('user/order/create', {
      partId: this.data.partId,
      groupId: this.data.groupId
    }, this, this.joinHandle, []).then((res) => {
      app.toggleLoading(false)
      let resultObj = res.data.data
      if (!res.data.success) {
        let statusCode = res.data.code.toString()
        if (statusCode === '10001') {
          wx.showToast({title: '该团购已过期', icon: 'none'})
        }
        else if (statusCode === '10002') {
          wx.showToast({title: '该团购已过期', icon: 'none'})
        }
        else if (statusCode === '10003') {
          wx.showToast({title: '团购已完成', icon: 'none'})
        }
        else if (statusCode === '10004') {
          wx.showToast({title: '团购失败，请重试!', icon: 'none'})
        }
        else if (statusCode === '10005') {
          wx.showToast({title: '团购失败，请重试!', icon: 'none'})
        }
        else if (statusCode === '10006') {
          wx.showToast({title: '团购已完成', icon: 'none'})
        }
        else if (statusCode === '10007') {
          wx.showToast({title: '您的余额不足', icon: 'none'})
        }
        else if (statusCode === '10008') {
          wx.showToast({title: '订单已支付', icon: 'none'})
        }
        else if (statusCode === '10009') {
          wx.showToast({title: '当前订单已关闭', icon: 'none'})
        }
        else if (statusCode === '10010') {
          wx.showToast({title: '您参与的团购已达上限', icon: 'none'})
        }
        else if (statusCode === '10011') {
          wx.showToast({title: '支付失败，无效支付', icon: 'none'})
        }
        else if (statusCode === '10022') {
          wx.showToast({title: '您已经团购过该商品', icon: 'none'})
        }
        return
      }
      let groupNo = resultObj.groupNo
      let newOrder = {'orderId': resultObj.orderNo}
      app.globalData.newOrders.push(newOrder)

      wx.requestPayment({
        timeStamp: resultObj.timeStamp,        //随机字符串，长度为32个字符以下。
        nonceStr: resultObj.nonceStr,         //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
        package: resultObj.package,      //签名算法，暂支持 MD5 signType: 'MD5',
        signType: 'MD5',
        paySign: resultObj.paySign,
        success: res => {
          app.toggleLoading(true)
          this.data.payWaitReflash = true
          this.refreshGroupState(false)
        },
        fail: res => {
          console.log(res)
          // wx.showToast({ title: '支付失败', icon: 'none' });
        },
        complete: res => {
        }
      })
    }).catch((errMsg) => {
      app.toggleLoading(false)
      console.log(errMsg)    //错误提示信息
    })
  },
  refreshGroupState(lastRequest = false) { //轮询现成团处理
    console.log("请求轮询刷新现成团数据....")
    let data = {groupNo: this.data.groupNo}
    if (this.data.share) data.share = 1
    app.post('user/order/info', data).then((res) => {
      let resultObj = res.data.data
      let exitingArr = resultObj.orderList
      this.refreshPersonList(exitingArr)
      let status = resultObj.groupStatus.toString()
      if (lastRequest) {            //如果是时间到的最后一次请求
        if (status === '2') this.groupSuccessHandle()
        else this.groupFailHandle()
      } else {
        if (this.data.payWaitReflash && status === '1') { //如果是支付等待刷新
          if (this.data.inList) { //检测到后端的支付状态已更新
            app.toggleLoading(false)
            wx.showToast({'title': '支付成功', 'icon': 'success', 'duration': 1500})
            this.data.payWaitReflash = false
          }
          else this.data.pollConut = 1//未到后端的支付状态更新,间隔一秒再刷新一次
        }
        else {
          if (status === '2') this.groupSuccessHandle()
          else if (status === '3') this.groupFailHandle()
        }
      }
    }).catch((errMsg) => {
      console.log(errMsg) //错误提示信息
    })
  },
  lookTicketHandle() {
    /*wx.showModal({
      title: '提示',
      showCancel: false,
      confirmText: '我知道了',
      confirmColor: '#ffab3a',
      content: '优惠券已发放，请到 原麦山丘公众号--会员中心--优惠券 中查看',
      success: function (res) {
        if (res.confirm) {
        }
      }
    })*/
    this.setData({
      showHint: true
    })
  },
  hideHint () {
    this.setData({
      showHint: false
    })
  },
  addInterval() { //添加计时器
    if (this.data.intervalId !== -1000) return
    this.data.pollConut = 0
    this.data.intervalId = setInterval(this.intervalHandle, 1000)
  },
  intervalHandle() { //计时器处理
    this.data.leftTime--
    if (this.data.leftTime <= 0) {
      this.timeOutHandle()
    }
    this.refreshExistingTime()
    this.data.pollConut++
    if (this.data.pollConut >= this.data.pollInterval) {
      this.data.pollConut = 0
      this.refreshGroupState()
    }
  },
  refreshExistingTime() {//刷新倒计时
    let timeChar = utils.secToTime(this.data.leftTime)
    this.setData({leftTimeStr: timeChar.split(':')})
  },
  timeOutHandle() {//团购时间到了
    console.log('拼团时间到')
    this.removeInterval()
    this.refreshGroupState(true)
    // this.setData({ groupState: '3' });
  },
  removeInterval() {//移除计时器
    if (this.data.intervalId === -1000) return
    clearInterval(this.data.intervalId)
    this.data.intervalId = -1000
  },
  groupSuccessHandle() {
    this.data.payWaitReflash = false
    app.toggleLoading(false)
    this.removeInterval()
    if (this.data.inList) wx.showToast({'title': '拼团成功', 'icon': 'success', 'duration': 1500})
    this.setData({groupState: '2'}, () => {
      this.updataGroupIconUrl()
      this.updataScrollViewH()
    })
  },
  groupFailHandle() {
    this.data.payWaitReflash = false
    app.toggleLoading(false)
    this.removeInterval()
    wx.showToast({'title': '拼团倒计时结束', 'icon': 'none', 'duration': 2000})
    this.setData({groupState: '3'}, () => {
      this.updataGroupIconUrl()
      this.updataScrollViewH()
    })
  },
  updataScrollViewH() {
    var query = wx.createSelectorQuery()
    query.select('#join-bottom').boundingClientRect()
    wx.getSystemInfo({
      success: win_res => {
        //获取滚动条的高度
        query.exec(dom_res => {
          if (!dom_res[0]) this.setData({scrollHeight: win_res.windowHeight})
          else {
            let bottom_h = dom_res[0].height
            this.setData({scrollHeight: win_res.windowHeight - bottom_h})
          }
        })
      }
    })
  },
  onShareAppMessage(options) {
    var shareObj = {
      title: "限时团购,等你加入~"
    }
    if (this.data.groupState.toString() === '1') {
      shareObj.path = '/pages/join/join?id=' + this.data.groupNo + '&share=1'
      //shareObj.imageUrl = this.data.topIcon
    } else {
      shareObj.path = '/pages/index/index'
    }
    return shareObj
  },
  toIndex() {
    wx.switchTab({url: '../index/index'})
  },
  scrollHandle(e) {
    if (e.detail.scrollTop <= 0) {
      this.slideHomeOut()
      return
    }
    if (this.data.scrollHeight + e.detail.scrollTop >= e.detail.scrollHeight) {
      this.slideHomeIn()
      return
    }
    if (e.detail.deltaY < 0) { //向上滚动
      this.slideHomeIn()
    }
    else this.slideHomeOut()
  },
  slideHomeOut() {
    if (this.homeStatus === 'out') return
    this.homeStatus = 'out'
    this.animation.opacity(1).translateX('0').step({duration: 1000})
    this.setData({animationData: this.animation.export()})
  },
  slideHomeIn() {
    if (this.homeStatus === 'in') return
    this.homeStatus = 'in'
    this.animation.opacity(0).translateX('150%').step({duration: 650})
    this.setData({animationData: this.animation.export()})
  },
  openNewGroup() {
    wx.navigateTo({
      url: `../open/open?id=${this.data.groupId}`
    })
  }
})

